<?php

namespace App\Models;

use App\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class WithdrawalLog extends Model
{
    protected $table ="c_withdrawal_logs";

    public function adminuser()
    {
        return $this->hasOne('App\Models\AdminUser','id','operation_uid');
    }


    /***
     *
     * 添加提现记录
     *
     */
    public function add($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
            $this->user_id = $filter['user_id'];
            $this->type = $filter['type'];
            $this->money = $filter['money'];
            $data = $this->save();
            if ($data) {
                if ($filter['type'] == 1) {
                    $reda = (new DoctorWorks())->where([['id', '=', $filter['user_id']]])->decrement("surplus", $filter['money']);
                } elseif ($filter['type'] == 2) {
                    $reda = (new User())->where([['id', '=', $filter['user_id']]])->decrement("surplus", $filter['money']);
                }
                if ($reda) {
                    DB::commit(); // 提交事务
                    return true;
                } else {
                    return false;
                    DB::rollback(); // 回滚事务
                }
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }
}
